if (typeof tzcpush === "undefined") {
    var tzcpush = {}
}

var tzcpush = {

 calprefs : Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService).getBranch("extensions.tzcpush."),

    onMenuItemCommand: function () {
        window.open(
		"chrome://tzcpush/content/pref.xul",
		"", 
		"chrome,centerscreen,resizable,toolbar", 
		null, null
	);
    
    },

go : function () {
	
Components.utils.import("chrome://tzcpush/content/toxml.js");

Components.utils.import("chrome://tzcpush/content/send.js");
	
//wbxml = String.fromCharCode(0x03,0x01,0x6A,0x00,0x45,0x5C,0x4F,0x50,0x03,0x43,0x61,0x6C,0x65,0x6E,0x64,0x61,0x72,0x00,0x01,0x4B,0x03,0x30,0x00,0x01,0x52,0x03,0x49,0x64,0x32,0x52,0x65,0x70,0x6C,0x61,0x63,0x65,0x00,0x01,0x01,0x01,0x01)
var synckey = tzcpush.calprefs.getCharPref("synckey")
var folderID = tzcpush.calprefs.getCharPref("folderID")
//wbxml = wbxml = wbxml.replace('Id2Replace', folderID)


if (folderID === "") {tzcpush.GetFolderId()}
else if (synckey === "0") {tzcpush.SyncZero()}
else {tzcpush.FromCal()}
},

GetFolderId : function () {
	
wbxml = String.fromCharCode(0x03,0x01,0x6a,0x00,0x00,0x07,0x56,0x52,0x03,0x30,0x00,0x01,0x01)
        Send(wbxml,callback,"FolderSync")

function callback(retwbxml) {

var folderID = tzcpush.FindFolder(retwbxml)


tzcpush.SyncZero(folderID)
}
},

SyncZero : function (folderID) {
	
	//folderID = tzcpush.calprefs.getCharPref("folderID")
	var outerwbxml = String.fromCharCode(0x03,0x01,0x6A,0x00,0x45,0x5C,0x4F,0x50,0x03,0x43,0x61,0x6C,0x65,0x6E,0x64,0x61,0x72,0x00,0x01,0x4B,0x03,0x30,0x00,0x01,0x52,0x03,0x49,0x64,0x32,0x52,0x65,0x70,0x6C,0x61,0x63,0x65,0x00,0x01,0x01,0x01,0x01)
    var wbxml = outerwbxml.replace('Id2Replace', folderID)
	Send(wbxml,callback,"Sync")
	
	function callback(retwbxml) {
	//alert(toxml(retwbxml))
	synckey = tzcpush.FindKey(retwbxml)
	//alert(synckey)
	tzcpush.calprefs.setCharPref("synckey",synckey)
	
	tzcpush.Fromcal()
}
	
	},

addtocal : function (wbxml) {
	Components.utils.import("chrome://tzcpush/content/toxml.js");
var xmlReader = Components.classes["@mozilla.org/saxparser/xmlreader;1"].createInstance(Components.interfaces.nsISAXXMLReader);

xmlReader.contentHandler = {
  // nsISAXContentHandler
 tmpchar : "" ,
 indadd : false,
 indelete : false,
 inmodify :false,
 week : false,
 month : false,
 Wom : "",
 Dow : "",
 hasWom : false,
 
  startDocument: function() {
    //alert("startDocument");
    this.inadd = false
    this.indelete = false
    this.inmodify = false
    this.tmpchar = ""
    this.week = false
    this.month = false
    this.Wom = ""
    this.hasWom = false
    this.Dow = ""
  },
  
  endDocument: function() {
    //alert("endDocument");
  },
  
  startElement: function(uri, localName, qName, attributes) {
    var attrs = [];
    for(var i=0; i<attributes.length; i++) {
      attrs.push(attributes.getQName(i) + "='" + 
                 attributes.getValue(i) + "'");
    }
    //alert(qName)
if (qName === "Add"){ this.inadd = true}
if (qName === "Delete") {this.indelete = true}
if (qName === "Change") {this.inmodify = true}


   
 
  },
  
  endElement: function(uri, localName, qName) {

if (this.indelete) {
	 //alert("in delete")
	 switch (qName) {
      case "ServerId":
	        //alert(this.tmpchar)
	        y = mycal.getItem(this.tmpchar,tzcpush.getListener)
	        
            break;
		}
	 }	 
	
if (this.inadd || this.inmodify) {
   
      switch (qName) {
      case "Subject":
	        event.title = this.tmpchar
            break;
      case "StartTime":
            sdate.icalString = this.tmpchar
            //event.startDate = sdate
            break;
      case "EndTime":
            edate.icalString = this.tmpchar
            //event.endDate = edate
            break;  
      case "Location":
            event.setProperty("LOCATION",this.tmpchar)
            break; 
      case "Body":
            event.setProperty("DESCRIPTION",this.tmpchar)
            break;            
      case "ServerId":
            if (this.inmodify) {
            y = mycal.getItem(this.tmpchar,tzcpush.getListener1)
            event = oldevent.clone()}
            event.id = this.tmpchar
            break;
            
      case "AllDayEvent": 
           if (this.tmpchar === "1") {         
          sdate.icalString = sdate.icalString.substring(0,8)
          edate.icalString = edate.icalString.substring(0,8)
            }
          
           
            break; 
      
      case "Reminder":
            myOffset = Components.classes["@mozilla.org/calendar/duration;1"].createInstance(Components.interfaces.calIDuration);
            myOffset.minutes = parseInt(this.tmpchar);
            myOffset.isNegative = true 
            Components.utils.import("resource://calendar/modules/calUtils.jsm");
            alarm = cal.createAlarm();
            alarm.related = Components.interfaces.calIAlarm.ALARM_RELATED_START;
            alarm.offset = myOffset
            alarm.action = "DISPLAY"
            event.addAlarm(alarm);
            break; 
            
      case "Type":
           
            Components.utils.import("resource://calendar/modules/calUtils.jsm");
            recInfo = cal.createRecurrenceInfo(event)
            recRule = cal.createRecurrenceRule()
             switch (this.tmpchar) {
		    case "0":
		    recRule.type = "DAILY"
		    break;
			case "1":	 
            recRule.type = "WEEKLY"
            this.week = true
            break;
            case "2":
            recRule.type = "MONTHLY"
            this.month = true
            break;
            case "3":
            recRule.type = "MONTHLY"
            this.month = true
            break;
            case "5":
            recRule.type = "YEARLY"
            break;
            case "6":
            recRule.type = "YEARLY"
            break;
		}
		  break;
		  
		  case "Interval":
		  recRule.interval = parseInt(this.tmpchar)
		  
          break;
          
          case "Recurrence":
              var daynum = sdate.jsDate.getDay()
              if (this.hasWom && this.Dow !== "127") {
			  //alert(this.Wom)
			  //var days = this.tmpchar + (this.Wom * 8)
			  var days = []
			  for (var i=0;i<7;i++)
             {
              x = Math.pow(2,i)
              //alert(Math.pow(2,i))
              y = this.Dow & x
              if (y !== 0) {days.push(i + 1 + (this.Wom * 8))}
               }
			 
			  recRule.setComponent("BYDAY", days.length, days)
			  
			  }
			  
			  else if (this.Dow === "127"){recRule.setComponent("BYMONTHDAY", 1, [-1])}
			            
              else if (Math.pow(2,daynum) !== this.Dow) { 
          		  
			  if (this.week) {
			  var days = []
			  for (var i=0;i<7;i++)
             {
              x = Math.pow(2,i)
              //alert(Math.pow(2,i))
              y = this.Dow & x
              if (y !== 0) {days.push(i + 1)}
               }
			  //alert(days + " " + days.length)
			  recRule.setComponent("BYDAY", days.length, days)
			  }
			  }
          
          
          recInfo.insertRecurrenceItemAt(recRule, 0)
          event.recurrenceInfo = recInfo
          break;
          
          case "WeekOfMonth":
          this.hasWom = true
          this.Wom = this.tmpchar
          
          break;
          
          case "DayOfWeek":
          
          this.Dow = this.tmpchar


          break;
          case "MonthOfYear":
          recRule.setComponent("BYMONTH", 1, [this.tmpchar])
          break;
        
}

}
if (qName === "Add"){
	 event.startDate = sdate
     event.endDate = edate
	mycal.addItem(event, null)
	event = Components.classes["@mozilla.org/calendar/event;1"].createInstance(Components.interfaces.calIEvent)
	this.inadd = false
	}
if (qName === "Delete"){
	//alert("Do Delete stuff")
	this.indelete = false
	}
if (qName === "Change"){
	//alert(event.id)
	oldevent.calendar.modifyItem(event,oldevent,null)
	event = Components.classes["@mozilla.org/calendar/event;1"].createInstance(Components.interfaces.calIEvent)
	this.inmodify = false
	}	

  },
   characters: function(value) {
  //alert("characters: " + value);
  this.tmpchar = value

  }, 

   
  processingInstruction: function(target, data) {
   
  },
  
  ignorableWhitespace: function(whitespace) {
    // don't care
  },
  
  startPrefixMapping: function(prefix, uri) {
    // don't care
  },
  
  endPrefixMapping: function(prefix) {
    // don't care
  },
  
  // nsISupports
  QueryInterface: function(iid) {
    if(!iid.equals(Components.interfaces.nsISupports) &&
       !iid.equals(Components.interfaces.nsISAXContentHandler))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  }
}

var xml = toxml(wbxml)

var calManager = Components.classes["@mozilla.org/calendar/manager;1"].getService(Components.interfaces.calICalendarManager);
var cals = calManager.getCalendars({});
var calname = tzcpush.calprefs.getCharPref("calID")

for ( calcount in cals) {
	 if (cals[calcount].name === calname) {break}
	 }
mycal = cals[calcount]
var event = Components.classes["@mozilla.org/calendar/event;1"].createInstance(Components.interfaces.calIEvent)
var sdate = Components.classes["@mozilla.org/calendar/datetime;1"].createInstance(Components.interfaces.calIDateTime)
var edate = Components.classes["@mozilla.org/calendar/datetime;1"].createInstance(Components.interfaces.calIDateTime)
xmlReader.parseFromString(xml,"text/xml")
//alert(event.title)


	
	},

FromCal : function () {
	folderID = tzcpush.calprefs.getCharPref("folderID")
	synckey = tzcpush.calprefs.getCharPref("synckey")
	wbxmlwkey = String.fromCharCode(0x03,0x01,0x6A,0x00,0x45,0x5C,0x4F,0x50,0x03,0x43,0x61,0x6C,0x65,0x6E,0x64,0x61,0x72,0x00,0x01,0x4B,0x03,0x53,0x79,0x6E,0x63,0x4B,0x65,0x79,0x52,0x65,0x70,0x6C,0x61,0x63,0x65,0x00,0x01,0x52,0x03,0x49,0x64,0x32,0x52,0x65,0x70,0x6C,0x61,0x63,0x65,0x00,0x01,0x1E,0x13,0x55,0x03,0x31,0x30,0x30,0x00,0x01,0x57,0x58,0x03,0x35,0x00,0x01,0x01,0x01,0x01,0x01)
	var wbxml = wbxmlwkey.replace('SyncKeyReplace', synckey);
	
    wbxml = wbxml = wbxml.replace('Id2Replace', folderID)
	Send(wbxml,callback,"Sync")
	
	function callback(retwbxml) {
	//alert(toxml(retwbxml))
	synckey = tzcpush.FindKey(retwbxml)
	//alert(synckey)
	tzcpush.calprefs.setCharPref("synckey",synckey)
	tzcpush.addtocal(retwbxml)
	}
	},

FindFolder : function (wbxml) {
	
	Components.utils.import("chrome://tzcpush/content/toxml.js");
	
    var start = 0
	var end
	var folderID
        var Scontact = String.fromCharCode(0x4A, 0x03) + '8' + String.fromCharCode(0x00, 0x01)
        var contact = wbxml.indexOf(Scontact)
       
        while (wbxml.indexOf(String.fromCharCode(0x48, 0x03), start) < contact)
{         
            start = wbxml.indexOf(String.fromCharCode(0x48, 0x03), start) + 2
            if (start === 1) {break} 
           
            end = wbxml.indexOf(String.fromCharCode(0x00), start)
            folderID = wbxml.substring(start, end)
            
        }
        
        tzcpush.calprefs.setCharPref("folderID",folderID)
        return folderID
    },

FindKey : function (wbxml) {
            var x = String.fromCharCode(0x4b, 0x03) //<SyncKey> Code Page 0
            if (wbxml.substr(5, 1) === String.fromCharCode(0x07))
{
                x = String.fromCharCode(0x52, 0x03) //<SyncKey> Code Page 7
            }
	    
            var start = wbxml.indexOf(x) + 2
            var end = wbxml.indexOf(String.fromCharCode(0x00), start)
            var synckey = wbxml.substring(start, end)
            return synckey

        },

getListener : {
        onOperationComplete: function(mycal, aStatus, aOperationType, aId, aDetail)
        {

        },
        onGetResult: function(mycal, aStatus, aItemType, aDetail, aCount, aItems)
        {
            
            if (!Components.isSuccessCode(aStatus)) {
                aborted = true;
                return;
            }
            if (aCount) {
                   for (var i=0; i<aCount; ++i) {
                    
                   //alert(aItems[i].title) //do all the zpush stuff here
                   //itemtodel = aItems[i]
                   z = mycal.deleteItem(aItems[i],null)
                
                }  
           }
        }
    },
    
getListener1 : {
        onOperationComplete: function(mycal, aStatus, aOperationType, aId, aDetail)
        {

        },
        onGetResult: function(mycal, aStatus, aItemType, aDetail, aCount, aItems)
        {
            
            if (!Components.isSuccessCode(aStatus)) {
                aborted = true;
                return;
            }
            if (aCount) {
                   for (var i=0; i<aCount; ++i) {
                    
                   //alert(aItems[i].title) //do all the zpush stuff here
                   //itemtodel = aItems[i]
                   //mycal.modifyItem(modevent,aItems[i],null)
                oldevent = aItems[i]
                }  
           }
        }
    },
}
